pacman::p_load(readxl, gifski, gapminder,
plotly, gganimate, tidyverse)Hands-on Exercise 3B
4.1 Overview
In this hands-on exercise, I learn how to create animated statistical graphics.
I try two methods:
- gganimate
- plotly
4.2 Getting Started
4.2.1 Loading the R packages
4.2.2 Importing the data
In this exercise, I use the Data worksheet from GlobalPopulation.xls.
col <- c("Country", "Continent")
globalPop <- read_xls("../data/GlobalPopulation.xls",
sheet = "Data") %>%
mutate(across(col, as.factor)) %>%
mutate(Year = as.integer(Year))4.3 Animated Data Visualisation: gganimate methods
4.3.1 Building a static population bubble plot
ggplot(globalPop,
aes(x = Old, y = Young,
size = Population,
colour = Country)) +
geom_point(alpha = 0.7,
show.legend = FALSE) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
labs(title = "Year: {frame_time}",
x = "% Aged",
y = "% Young")
4.3.2 Building the animated bubble plot
I add transition_time(Year) and ease_aes('linear').
p_anim <- ggplot(globalPop,
aes(x = Old, y = Young,
size = Population,
colour = Country)) +
geom_point(alpha = 0.7,
show.legend = FALSE) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
labs(title = "Year: {frame_time}",
x = "% Aged",
y = "% Young") +
transition_time(Year) +
ease_aes("linear")
p_anim
(Optional) If I want to render as GIF:
animate(p_anim, renderer = gifski_renderer())
4.4 Animated Data Visualisation: plotly
Both ggplotly() and plot_ly() can support animation by frame.
4.4.1 Building an animated bubble plot: ggplotly() method
gg <- ggplot(globalPop,
aes(x = Old,
y = Young,
size = Population,
colour = Country)) +
geom_point(aes(size = Population,
frame = Year),
alpha = 0.7) +
scale_colour_manual(values = country_colors) +
scale_size(range = c(2, 12)) +
labs(x = "% Aged",
y = "% Young") +
theme(legend.position = "none")
ggplotly(gg)4.4.2 Building an animated bubble plot: plot_ly() method
bp <- globalPop %>%
plot_ly(x = ~Old,
y = ~Young,
size = ~Population,
color = ~Continent,
sizes = c(2, 100),
frame = ~Year,
text = ~Country,
hoverinfo = "text",
type = "scatter",
mode = "markers") %>%
layout(showlegend = FALSE)
bp4.5 Reference
- gganimate documentation
- plotly for R documentation